
package sk.stuba.fei.ut.snmpmanager;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.UUID;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;

public class pollingService extends Service
{
	public static final String TAG = pollingService.class.getSimpleName();
	public Boolean ping_result = false;

	String AgentID;
	String IP_address;
	String Agent_name;
	Boolean NetStatus;

	@Override
	public IBinder onBind( Intent intent )
	{
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate()
	{
		super.onCreate();

		// EDIT BY ERIK: use of AgentManager-> AgentManager.get(context).XY
		// get list of all agents
		ArrayList<Agent> list = AgentManager.get( getApplicationContext() )
				.getAgents();

		for ( Agent agent : list )
		{
			if ( agent.isPolled() ) // poll all agents with enabled polling
			{

				AgentID = agent.getID().toString();
				IP_address = agent.getIpv4Address();
				Agent_name = agent.getTitle();
				NetStatus = isNetworkOnline(); // check for network access

				if ( NetStatus == true )
				{
					new Ping_async().execute( IP_address, Agent_name, AgentID ); // execute
																					// ping
																					// in
																					// the
																					// background

					stopSelf(); // self stop pollingService
				}
				else
				{
					Log.d( TAG, "polling service has no network access" );
				}

			}

		}
		;
	};

	private class Ping_async extends AsyncTask<String, Void, String>
	{

		protected String doInBackground( String... params )
		{

			try
			{
				ping_result = InetAddress.getByName( params[0] ).isReachable(
						1000 );
				Log.d( TAG,
						"device " + params[0] + " is reachable: "
								+ String.valueOf( ping_result ) );
				Log.d( TAG, params[1] );

				if ( ping_result == false )
				{
					PublishNotification( params[0], params[1], params[2] );
				}

				return ( String.valueOf( ping_result ) );
			}
			catch ( Throwable t )
			{
				Log.e( "AsyncTask", "Crash", t );
				throw new RuntimeException( t );
			}
		}

		protected void onPostExecute( String... results )
		{

		}
	}

	// finds out whether application has internet access or not
	public boolean isNetworkOnline()
	{
		boolean status = false;
		try
		{
			ConnectivityManager cm = ( ConnectivityManager ) getSystemService( Context.CONNECTIVITY_SERVICE );
			NetworkInfo netInfo = cm.getNetworkInfo( 0 );
			if ( netInfo != null
					&& netInfo.getState() == NetworkInfo.State.CONNECTED )
			{
				status = true;
			}
			else
			{
				netInfo = cm.getNetworkInfo( 1 );
				if ( netInfo != null
						&& netInfo.getState() == NetworkInfo.State.CONNECTED )
					status = true;
			}
		}
		catch ( Exception e )
		{
			Log.e( TAG, "exception", e );
			return status;
		}
		return status;
	}

	public void onDestroy()
	{
		super.onDestroy();
		// Log.d(TAG, "polling Destroy'd");
	}

	public String[] PublishNotification( String... ping_returns )
	{

		Intent i = new Intent( getBaseContext(), AgentPagerActivity.class );
		i.putExtra( AgentFragment.EXTRA_AGENT_ID, UUID.fromString( ping_returns[2] ) );
		PendingIntent pIntent = PendingIntent.getActivity( this, 0, i, 0 );

		Notification n = new Notification.Builder( this )
				.setContentTitle(
						ping_returns[1]
								+ getString( R.string.pollingService_notReachable ) )
				.setContentText(
						getString( R.string.pollingService_agentDetails )
								+ getString( R.string.polingService_agentIP )
								+ ping_returns[0] )
				.setSmallIcon( R.drawable.ic_launcher )
				.setContentIntent( pIntent ).setAutoCancel( true ).build();
		// .addAction(R.drawable.ic_launcher, "Go to agent", pIntent)
		NotificationManager notificationManager = ( NotificationManager ) getSystemService( NOTIFICATION_SERVICE );
		int notifyID = ( UUID.fromString( ping_returns[2] ) ).hashCode(); // generate
																			// unique
																			// hash
																			// values
																			// based
																			// on
																			// agent's
																			// UUID
		notificationManager.notify( notifyID, n );

		return ping_returns;
	}

}
